using System.Text.Json;

namespace DidaManager.Models
{
    public class Register
    {
        public string? Name { get; set; }
        public int Id { get; set; }
    }

    public class DeviceType
    {
        public string? Name { get; set; }
        public int Id { get; set; }
        public string? Type { get; set; }
        public List<string>? Regs { get; set; }
    }

    public class DeviceRegisterConfiguration
    {
        public List<Register>? Regs { get; set; }
        public List<DeviceType>? RegType { get; set; }
    }

    public class DeviceRegisterConfigManager
    {
        private static DeviceRegisterConfiguration? _configuration;
        private static readonly string ConfigPath = Path.Combine("config", "device_registers.json");

        public static DeviceRegisterConfiguration Configuration
        {
            get
            {
                if (_configuration == null)
                {
                    _configuration = new DeviceRegisterConfiguration
                    {
                        Regs = new List<Register>(),
                        RegType = new List<DeviceType>()
                    };
                    LoadConfiguration();
                }
                return _configuration ?? new DeviceRegisterConfiguration();
            }
        }

        /// <summary>
        /// 加载配置文件
        /// </summary>
        public static void LoadConfiguration()
        {
            try
            {
                string jsonContent = File.ReadAllText(ConfigPath);
                // 1.先解析,在获取regs字段  
                var jsonObject = JsonDocument.Parse(jsonContent);
                var regs = jsonObject.RootElement.GetProperty("regs");

                // Ensure _configuration.Regs is not null before adding items  
                _configuration!.Regs ??= new List<Register>();

                foreach (var reg in regs.EnumerateArray())
                {
                    // reg是一个对象，需要获取对应字段name和id的值  
                    var name = reg.GetProperty("name").GetString();
                    var id = reg.GetProperty("id").GetInt32();
                    var register = new Register { Name = name, Id = id };
                    _configuration.Regs.Add(register);
                }

                // Ensure _configuration.RegType is not null before assigning  
                _configuration.RegType ??= new List<DeviceType>();

                // 2.获取RegType字段  
                foreach (var regType in jsonObject.RootElement.GetProperty("regType").EnumerateArray())
                {
                    var name = regType.GetProperty("name").GetString();
                    var id = regType.GetProperty("id").GetInt32();
                    var type = regType.GetProperty("type").GetString();
                    var regsTemp = regType.GetProperty("regs").EnumerateArray().Select(r => r.GetInt32()).ToList();

                    // 需要将regLists中的id和Regs中的id进行匹配，如果匹配到，则将Regs中的name添加到regLists中
                    var regLists = new List<string>();
                    foreach (var reg in regsTemp)
                    {
                        var regId = Configuration.Regs?.FirstOrDefault(r => r.Id == reg)?.Name;
                        if (regId != null)
                        {
                            regLists.Add(regId);
                        }
                    }
                    var deviceType = new DeviceType { Name = name, Id = id, Type = type, Regs = regLists };
                    _configuration.RegType.Add(deviceType);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Error loading device register configuration: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取所有寄存器
        /// </summary>
        public static List<Register> GetAllRegisters()
        {
            return Configuration.Regs ?? new List<Register>();
        }

        /// <summary>
        /// 获取所有设备类型
        /// </summary>
        public static List<DeviceType> GetAllDeviceTypes()
        {
            // Fix for CS8604 and CS8603: Ensure RegType is not null and handle null Types
            return (Configuration.RegType ?? new List<DeviceType>()).OrderBy(dt => dt.Id).ToList();
        }

        /// <summary>
        /// 根据寄存器ID获取设备类型
        /// </summary>
        public static List<DeviceType> GetDeviceTypesByRegister(int registerId)
        {
            return GetAllDeviceTypes().Where(dt => dt.Regs?.Any(r => r == registerId.ToString()) == true).ToList();
        }

        /// <summary>   
        /// 根据设备类型获取寄存器
        /// </summary>
        public static List<Register> GetRegistersByDeviceType(int deviceTypeId)
        {
            var deviceType = GetAllDeviceTypes().FirstOrDefault(dt => dt.Id == deviceTypeId);
            if (deviceType == null || deviceType.Regs == null) return new List<Register>();

            return Configuration.Regs?.Where(r => deviceType.Regs.Any(rt => rt == r.Name)).ToList() ?? new List<Register>();
        }

        /// <summary>
        /// 根据寄存器名称获取寄存器ID
        /// </summary>
        public static int GetRegisterIdByName(string registerName)
        {
            return Configuration.Regs?.FirstOrDefault(r => r.Name == registerName)?.Id ?? -1;
        }

        /// <summary>
        /// 根据连接类型获取设备类型
        /// </summary>
        public static List<string> GetDeviceTypesByConnectionType(string connectionType)
        {
            var deviceTypes = GetAllDeviceTypes()
                .Where(dt => dt.Type?.Equals(connectionType, StringComparison.OrdinalIgnoreCase) == true)
                .OrderBy(dt => dt.Id)
                .Select(dt => dt.Name ?? string.Empty)
                .ToList();

            return deviceTypes;
        }

        /// <summary>
        /// 根据设备id，获取端口加载设备的寄存器
        /// </summary>
        public static List<Register> GetRegistersByDeviceId(string deviceId)
        {
            return GetAllRegisters().Where(r => r.Id == int.Parse(deviceId)).ToList();
        }
    }
} 